<template>
    <div class="resetPassword">
        <header>
            <span class="title">重置密码</span>
            <i class="iconfont icon-guanbi closeIcon" @click="handleCancel"></i>
        </header>
        <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="80px" class="eq-reset-password"
            :size="formSize" status-icon>
            <el-form-item label="旧密码" prop="oldPassword">
                <el-input v-model="formData.oldPassword" type="password" placeholder="请输入旧密码" />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
                <el-input v-model="formData.newPassword" type="password" placeholder="请输入新密码" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码" />
            </el-form-item>
            <div class="btns">
                <span class="cancelBtn" @click="handleCancel">取消</span>
                <span class="confirmBtn" @click="handleConfirm(ruleFormRef)">确定</span>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store/modules/user';

import * as server from '@/api/modules/user';
import * as local from '@/utils/cache/localStorage';

import { apiFn } from '@/utils/utilFns';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['closeDialog']);

const userStore = useUserStore();

const router = useRouter();

const ruleFormRef = ref(null);
const formData = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
});

// 新密码校验
const validatePass = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请输入新密码!"));
    } else if (value.length < 6) {
        callback(new Error("请输入至少6位数密码!"));
    } else if (value == formData.oldPassword) {
        callback(new Error("新密码不能和旧密码一致!"));
    }else{
        callback();
    }
};

// 确认新密码校验
const validatePass2 = (rule, value, callback) => {
    if (value === "") {
        callback(new Error("请再次输入密码!"));
    } else if (value !== formData.newPassword) {
        callback(new Error("两次输入密码不一致!"));
    } else {
        callback();
    }
};

const rules = reactive({
    oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
    newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
    confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }]
});

// 取消
const handleCancel = () => {
    emit('closeDialog');
};

// 确定
const handleConfirm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            submitForm();
        } else {
            console.log('error submit!', fields)
        }
    })
};

// 提交
const submitForm = () => {
    
    const params = {
        id: local.getUser().id,
        password: formData.oldPassword,
        newPassword: formData.newPassword
    };
    apiFn(server.updatePassword, params)
        .then(res => {
            ElMessage({
                message: '密码重置成功，请重新登陆！',
                grouping: true,
                type: 'success',
            });
            handleLogout();
        }).catch(err => {
            ElMessage({
                message: '密码重置失败！',
                grouping: true,
                type: 'error',
            });
        })
};

// 退出登陆
const handleLogout = async () => {
    userStore.logout().then(router.push('/login'))
};

</script>

<style lang="scss" scoped>
@import './ResetPassword.scss';
</style>